#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

typedef struct {
	int tosort;
	int index;
} tuple;

class Comparer
{
public:
	bool operator () (const tuple & left, const tuple & right)
	{
		return left.tosort < right.tosort;
	}
};

int processItem(string item, int n)
{
	int result = 0;
	for(int i = 0; i < n; i++)
	{
		for(int j = i + 1; j < n; j++)
		{
			if(item[i] > item[j])
				result++;
		}
	}
	return result;
}

int main()
{
	int n, m;
	cin >> n >> m;
	vector<string> data;
	string temp;
	vector<tuple> processData;
	tuple t;
	for(int i = 0; i < m; i++)
	{
		cin >> temp;
		data.push_back(temp);
		t.index = i;
		t.tosort = processItem(temp, n);
		processData.push_back(t);
	}

	sort(processData.begin(), processData.end(), Comparer());

	for(int i = 0; i < m; i++)
	{
		cout << data[processData[i].index] << endl;
	}
	

	return 0;
}